package top.waikin.mooc.admin.config;


import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import top.waikin.mooc.admin.service.AdminRoleRelationService;
import top.waikin.mooc.admin.service.AdminService;
import top.waikin.mooc.common.api.CommonResult;
import top.waikin.mooc.common.api.ResultCode;
import top.waikin.mooc.entity.Admin;
import top.waikin.mooc.entity.Permission;
import top.waikin.mooc.security.config.BaseSecurityConfig;
import top.waikin.mooc.security.util.PrivilegeUtil;

import java.util.List;


@Configuration
public class SecurityConfig extends BaseSecurityConfig {

    @Autowired
    AdminService adminService;

    @Autowired
    AdminRoleRelationService adminRoleRelationService;


    @Override
    public void run(Object r) {
        // 判断用户登录状态
        if (!PrivilegeUtil.isLogin()) {
            SaRouter.back(JSONUtil.parseObj(CommonResult.failed(ResultCode.UNAUTHORIZED), false));
        }
        Admin admin = adminService.getCurrentAdmin();
        // 判断用户是否被禁用
        if (ObjectUtil.notEqual(admin.getStatus(), 1)) {
            LOGGER.warn("admin:{},baned", admin.getTelephone());
            SaRouter.back(JSONUtil.parseObj(CommonResult.failed("该用户被禁用"), false));
        }
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        requestAttributes.setAttribute("telephone", admin.getTelephone(), RequestAttributes.SCOPE_REQUEST);
        // 判断当前访问资源是否存在用户可访问的资源列表中
        String method = SaHolder.getRequest().getMethod();
        String requestPath = SaHolder.getRequest().getRequestPath().replaceFirst("/$", "");
        List<Permission> adminPermissionList = adminService.getPermissionList(admin.getId());
        for (Permission permission :
                adminPermissionList) {
            if (SaRouter.isMatch(new SaHttpMethod[]{SaHttpMethod.toEnum(permission.getMethod())}, method)
                    && SaRouter.isMatch(permission.getUrl(), requestPath)) {
                return;
            }
        }
        LOGGER.warn("admin:{},forbidden,method:{},url:{}", admin.getTelephone(), method, requestPath);
        SaRouter.back(JSONUtil.parseObj(CommonResult.failed(ResultCode.FORBIDDEN), false));
    }

}
